<?php

//redis单例
final class RedisDB
{
    const REDISHOST = '127.0.0.1';
    const REDISPORT = '6379';
    const REDISPASWORD = '';
    const REDISDBNAME = 0;
    private static $_obj = null;

    private function __construct()
    {
    }

    private function __clone()
    {
    }//禁止克隆

    private static function connect_redis($dbname = null)
    {
        try {
            self::$_obj = new redis();
            self::$_obj->connect(self::REDISHOST, self::REDISPORT);
            if (self::REDISPASWORD) {
                self::$_obj->auth(self::REDISPASWORD);
            }
            if ($dbname) {
                $dbname = (int)$dbname;
                self::$_obj->select($dbname);
            } else {
                self::$_obj->select(self::REDISDBNAME);
            }
        } catch (Exception $e) {
            exit($e->getMessage() . '<br/>');
        }
        return self::$_obj;
    }

    public static function getRedis()
    {
        if (!self::$_obj) {
            self::$_obj = self::connect_redis();
        }
        return self::$_obj;
    }
}